<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-descriptions
      class="global-descriptions"
      title="基本信息"
      border
      :column="1"
    >
      <el-descriptions-item label="渠道商">
        <ProfilePanel
          v-if="detailData"
          :avatar="detailData.avatar"
          :nickname="detailData.nickname"
        />
      </el-descriptions-item>
      <el-descriptions-item label="备注">
        {{ detailData?.remark }}
      </el-descriptions-item>
      <el-descriptions-item label="手机号">
        {{ detailData?.mobile }}
      </el-descriptions-item>
      <el-descriptions-item label="真实姓名">
        {{ detailData?.realname }}
      </el-descriptions-item>
      <el-descriptions-item label="微信号">
        {{ detailData?.weixin }}
      </el-descriptions-item>
    </el-descriptions>

    <el-tabs v-model="formData.type" style="margin-top: 24px">
      <el-tab-pane label="佣金" name="1"></el-tab-pane>
      <el-tab-pane label="积分" name="2"></el-tab-pane>
    </el-tabs>

    <el-form
      ref="formRef"
      label-position="right"
      label-width="80px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="当前余额">
        <PipeMoney :type="formData.type" :money="getOldMoney" />
      </el-form-item>
      <el-form-item label="变化" prop="typeOperate">
        <el-radio-group v-model="typeOperate">
          <el-radio label="增加" />
          <el-radio label="减少" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="充值数目" prop="money">
        <el-input v-model="formData.money" v-decimal></el-input>
        <div style="margin-top: 8px" v-if="formData.money">
          充值后剩余：<PipeMoney :type="formData.type" :money="getNewMoney" />
        </div>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="getRemark"
          type="textarea"
          :rows="4"
          :maxlength="160"
          show-word-limit
          readonly
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <PipeResetBtn
        :formEl="formRef"
        @clear="handleClickReset"
        :loading="isLoading"
        >重置</PipeResetBtn
      >
      <el-button
        type="primary"
        @click="handleClickSubmit(formRef)"
        :loading="isLoading"
        >确定充值</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { PropType, computed, reactive, ref, watch } from 'vue';
import type { ElForm } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUsersDetail } from '@/apis/users';
import { calcAdd, calcSubtract } from '@/utils/util';
import { createRecharge } from '@/apis/user-recharge';

// 加载状态
const isLoading = ref(false);

const detailData = ref<API.user.EntitySchema>();

// 表单 - ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const GetFormData = (): API.userRecharge.EntityDto => ({
  userOwnId: '',
  type: '1',
  money: '',
  remark: ''
});
const formData = ref(GetFormData());

const typeOperate = ref<'增加' | '减少'>('增加');

// 表单 - 验证
const formRules = reactive({
  money: [{ required: true, trigger: 'blur', message: '请输入数目' }]
});

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '30%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  rowData: {
    type: Object as PropType<API.user.TableData>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// 获取详情
const requestDataDetail = () => {
  isLoading.value = true;
  getUsersDetail(props.rowData.ownId!)
    .then((res) => {
      isLoading.value = false;
      detailData.value = res.data;

      // 还原数据
      formData.value = GetFormData();
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;
    requestDataDetail();
  },
  {
    immediate: true
  }
);

const getOldMoney = computed(() => {
  return (
    (formData.value.type === '1'
      ? detailData.value?.bonus
      : detailData.value?.credits) || '0'
  );
});

// 计算变化
const getNewMoney = computed(() => {
  const operateFN = typeOperate.value === '增加' ? calcAdd : calcSubtract;
  return operateFN(getOldMoney.value, formData.value.money || 0);
});

// 组装备注
const getRemark = computed(() => {
  const unit = formData.value.type === '1' ? '元' : '积分';
  const nickname = detailData.value?.nickname || '';
  const money = formData.value.money || '0';
  const oldMoney = getOldMoney.value;
  const newMoney = getNewMoney.value;

  return `【会员充值::${nickname}】当前余额：${oldMoney}${unit}，${typeOperate.value}了${money}${unit}，充值后剩余：${newMoney}${unit}；`;
});

// btn - reset
const handleClickReset = () => {
  // 还原数据
  formData.value = GetFormData();
};

// btn - submit
const handleClickSubmit = async (
  formEl: InstanceType<typeof ElForm> | undefined
) => {
  if (+getNewMoney.value < 0) {
    return await ElMessageBox.alert('充值数目有无，请核对', '会员充值', {
      confirmButtonText: '确定'
    });
  }

  try {
    await ElMessageBox.confirm('充值后不可撤销，是否确认充值？', '会员充值', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch (error) {
    return;
  }

  formData.value.userOwnId = detailData.value?.ownId!;
  formData.value.remark = getRemark.value;
  const dataOpt = {
    ...formData.value
  };
  if (typeOperate.value === '减少') dataOpt.money = `-${dataOpt.money}`;

  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;
    submitDataAdd(dataOpt);
  });
};

// submit - add
const submitDataAdd = (dataOpt: API.userRecharge.EntityDto) => {
  isLoading.value = true;
  createRecharge(dataOpt)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
</script>

<style lang="scss" scoped>
// .wrapper-profile-panel {
//   width: 256px;
//   padding: 8px;
//   // border: 1px solid var(--el-border-color);
//   border: 1px solid var(--el-border-color-lighter);
// }
</style>
